package com.moonshineproject.commands
{
	import com.moonshineproject.GlobalEventDispatcher;
	import com.moonshineproject.IDEModel;
	import com.moonshineproject.editor.BasicTextEditor;
	import com.moonshineproject.events.OpenFileEvent;
	import com.moonshineproject.plugin.events.EditorPluginEvent;
	import com.moonshineproject.plugin.events.FilePluginEvent;
	import com.moonshineproject.view.IContentWindow;
	import com.moonshineproject.view.notifier.ActionNotifier;

	import flash.events.Event;
	import flash.filesystem.File;

	public class OpenFileCommand implements ICommand
	{
		protected var model:IDEModel;
		protected var file:File;
		protected var atLine:int = -1;

		public function execute(event:Event):void
		{
			ActionNotifier.getInstance().notify("Open file");
			model = IDEModel.getInstance();

			if (event is OpenFileEvent)
			{
				var e:OpenFileEvent = event as OpenFileEvent;
				if (e.file)
				{
					file = e.file;
					if (e.atLine > -1)
						atLine = e.atLine;
					openFile();
					return;
				}
			}
			file = new File();
			file.addEventListener(Event.SELECT, openFile);
			file.browseForOpen("Open File");
		}

		protected function openFile(event:Event=null):void
		{ 
			// If file is open already, just focus that editor.
			for each (var contentWindow:IContentWindow in model.editors)
			{
				var ed:BasicTextEditor = contentWindow as BasicTextEditor;
				if (ed
					&& ed.currentFile
					&& ed.currentFile.nativePath == file.nativePath)
				{
					model.activeEditor = ed;
					if (atLine > -1)
						ed.getEditorComponent().scrollTo(atLine);
					return;
				}
			}

			var ged:GlobalEventDispatcher = GlobalEventDispatcher.getInstance();

			// Let plugins know that we're opening a file & abort it if they want to render it themselves
			var plugEvent:FilePluginEvent = new FilePluginEvent(FilePluginEvent.EVENT_FILE_OPEN, file);
			ged.dispatchEvent(plugEvent);
			if (plugEvent.isDefaultPrevented())
				return;

			var editor:BasicTextEditor = new BasicTextEditor();

			// Let plugins hook in syntax highlighters & other functionality
			var editorEvent:EditorPluginEvent = new EditorPluginEvent(EditorPluginEvent.EVENT_EDITOR_OPEN);
			editorEvent.editor = editor.getEditorComponent();
			editorEvent.file = file;
			ged.dispatchEvent(editorEvent);

			editor.open(file);
			if (atLine > -1)
				editor.scrollTo(atLine);

			if (model.activeEditor.isEmpty())
			{
				model.editors.removeItemAt(model.editors.getItemIndex(model.activeEditor));
				model.editors.addItem(editor);
			}
			else
			{
				model.editors.addItem(editor);
			}
		}

	}
}